
var Server = {

    publish: "http://172.17.0.3:1985/rtc/v1/publish/",
    play:    "http://172.17.0.3:1985/rtc/v1/play/",
    webrtc:  "webrtc://172.17.0.3/",
}

var room = {
    
    roomId: "",
    userId: "",
    localRtc: null,
    remoteRtcs: [],
}

var containers = {
    audio: true,
    video: {
        width: 320,
        height: 360,
    },
}

async function EnterRoom() {

    inputMessage = document.getElementById("roomId")
    console.log(inputMessage.value)
    var roomId = inputMessage.value
    if (roomId.length == 0) {

        alert("roomId is empty")
        return;
    }
    document.getElementById("enterRoom").disabled = true
    room.roomId = roomId

    room.localRtc = new RTCPeerConnection(null)

    var stream = await navigator.mediaDevices.getUserMedia(containers)
    room.localRtc.addStream(stream);

    localVideo = document.getElementById('localVideo')
    localVideo.srcObject = stream
    localVideo.play();

    var offer = await room.localRtc.createOffer()
    await room.localRtc.setLocalDescription(offer);
    console.log(room.localRtc.localDescription)

    PublishStream();
}

async function PublishStream() {

    var request = new XMLHttpRequest()
    var data = {
        api:Server.publish,
        clientip:null,
        sdp: room.localRtc.localDescription.sdp,
        tid: Number(parseInt(new Date().getTime()*Math.random()*100)).toString(16).substring(0,7),
        streamurl: "",
    }
    data.streamurl = Server.webrtc + room.roomId + "/" + data.tid
    room.userId = data.tid

    body = JSON.stringify(data);
    request.open('POST', Server.publish, true);
    request.onload = function(response) {

        // console.log(response)
        var body = JSON.parse(response.currentTarget.responseText)
        console.log(body.sdp)

        room.localRtc.setRemoteDescription({
            type:'answer',
            sdp:body.sdp
        });
        room.remoteRtcs = new Array();

        PlayStream(room.userId);
    }
    request.send(body);
}

async function PlayStream(tid) {

    size = room.remoteRtcs.length;
    if (size >= 4) {

        return;
    }
    room.remoteRtcs.push(new RTCPeerConnection(null));

    var optional =  {
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1,
    };
    room.remoteRtcs[size].addEventListener('addstream', function(event){

        console.log(event);
        video = document.getElementById(String(size)); 
        video.srcObject = event.stream
        video.play();

        PlayStream(room.userId);
    });

    var offer = await room.remoteRtcs[size].createOffer(optional)

    console.log(offer.sdp)

    room.remoteRtcs[size].setLocalDescription(offer);

    var request = new XMLHttpRequest()
    var data = {
        streamurl: Server.webrtc + room.roomId + "/" + tid,
        api: Server.play,
        clientip: null,
        sdp: offer.sdp,
        tid: tid,
    }
    body = JSON.stringify(data);
    request.open('POST', Server.play, true);
    request.onload = function(response) {

        var body = JSON.parse(response.currentTarget.responseText)
        console.log(body.sdp)

        room.remoteRtcs[size].setRemoteDescription(

            {type: 'answer', sdp:body.sdp}
        );
    }
    request.send(body);
}
